<?php
/**
 * 配置管理控制器
 * ===============================================
 * @copyright 深圳市顶速网络科技有限公司  http://fasttop.top
 * ===============================================
 * @author: Ketity <970564173@qq.com>
 * @date: 2015-5-27
 */
namespace Admin\Controller;
class ConfigController extends BaseController {
	
	public function _initialize() {
		parent::_initialize ();
		$this->assign ( 'type', C ( 'CONFIG_TYPE_LIST' ) ); //配置类型
		$this->assign ( 'group', C ( 'CONFIG_GROUP_LIST' ) ); //配置所属组
	}
	
	/**
	 * 配置列表
	 */
	public function index() {
		$where = array ();
		$config_group = I ( 'get.config_group' );
		if ($config_group) {
			$where ['config_group'] = $config_group;
			$this->assign ( 'config_group', $config_group );
		}
		$config_name = I ( 'post.config_name' );
		if ($config_name) {
			$where ['config_name'] = array ('like', '%' . $config_name . '%' );
			$this->assign ( 'config_name', $config_name );
		}
		$count = D ( 'Config' )->where ( $where )->count ();
		$limit = $this->paging ( $count );
		$list = D ( 'Config' )->where ( $where )->order ( 'sort_order desc,id asc' )->limit ( $limit )->select ();
		$this->assign ( 'list', $list );
		$this->display ();
	}
		
	/**
	 * 网站设置页面
	 */
	public function group() {
		$groupid = I ( 'get.groupid' );
		$groupid = empty ( $groupid ) ? 1 : $groupid;
		if ($groupid) {
			$where ['config_group'] = $groupid;
			$this->assign ( 'groupid', $groupid );
		}
		$where ['status'] = 1;
		$field = 'id,config_name,config_title,config_extra,config_value,config_remark,config_type';
		$list = D ( 'Config' )->getConfig ( $field, $where );
		foreach ( $list as $k => $v ) {
			if (! empty ( $v ['config_extra'] )) {
				$list [$k] ['config_extra'] = $this->_parseConfigAttr ( $v ['config_extra'] );
			}
		}
		$this->assign ( 'list', $list );
		$this->display ();
	}
	
	/**
	 * 分析枚举类型配置
	 * @param string $string
	 */
	private function _parseConfigAttr($string) {
		$array = preg_split ( '/[,;\r\n]+/', trim ( $string, ',;\r\n' ) );
		if (is_array ( $array )) {
			foreach ( $array as $val ) {
				list ( $k, $v ) = explode ( ':', $val );
				$value [$k] = $v;
			}
		} else {
			$value = $array;
		}
		return $value;
	}
	
	/**
	 * 更新网站设置
	 */
	public function save() {
		if (IS_POST && isset ( $_POST ['dosubmit'] )) {
			$config = I ( 'post.config' );
			if (is_array ( $config )) {
				foreach ( $config as $k => $v ) {
					$map ['config_name'] = $k;
					$data ['config_value'] = $v;
					D ( 'Config' )->editConfig ( $data, $map );
				}
				$configList = D ( 'Config' )->getList ();
				S ( 'DB_CONFIG_DATA', $configList ); //缓存配置
				$this->success ( L ( 'success_edit' ) );
			}
		} else {
			$this->error ( L ( 'error_illegal_operation' ) );
		}
	}
	
}